package com.whisperly.echotalk.starryb.schemas;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.appsflyer.AppsFlyerLib;
import com.appsflyer.attribution.AppsFlyerRequestListener;
import com.whisperly.echotalk.bllmodel.RegisterDto;
import com.whisperly.echotalk.bllmodel.RegisterResponse;
import com.whisperly.echotalk.bllmodel.ResultBody;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.BaseURL;
import com.whisperly.echotalk.starryb.utils.Mutual;
import com.whisperly.echotalk.starryb.utils.SendGmail;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class Register extends AppCompatActivity {
    private EditText user_name, user_email, et_psw, et_cpsw, verification_code;
    private Button register, btnSendCode;
    private TextView login;
    private CheckBox checkbox_agree;
    private Toast currentToast;
    private CountDownTimer countDownTimer;
    private String userInputCode;
    private Toast current;
    private View loadingView;

    private static final String TAG = "Register";

    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        AppsManager.addActivity(this);

        user_name = findViewById(R.id.user_name);
        user_email = findViewById(R.id.user_email);
        et_psw = findViewById(R.id.et_psw);
        et_cpsw = findViewById(R.id.et_cpasw);
        register = findViewById(R.id.register);
        login = findViewById(R.id.login);
        btnSendCode = findViewById(R.id.btn_send_code);
        verification_code = findViewById(R.id.verification_code);
        checkbox_agree = findViewById(R.id.checkbox_agree);
        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);

        TextView textView = findViewById(R.id.text_privacy);
        String fullText = getString(R.string.read_and_agree_to_the_terms_of_service);
        SpannableString spannableString = new SpannableString(fullText);

        btnSendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = user_email.getText().toString().trim();
                if (isValidEmail(email)) {
                    startCountDown();
                    // 调用发送验证码的方法
                    SendGmail.generateCode(email);
                    SendGmail.sendEmail(email, v, Register.this);
                } else {
                    user_email.setError(getString(R.string.invalid_email_address));
                }

            }
        });


        setSpanWithClickAndColor(spannableString, "Blink Chat", () -> {

            openWebView(BaseURL.BASE_URL, "Blink Chat");
        });
        setSpanWithClickAndColor(spannableString, getString(R.string.User_Agreement), () -> {

            openWebView(BaseURL.TERMS_CONDITIONS, getString(R.string.User_Agreement));
        });
        setSpanWithClickAndColor(spannableString, getString(R.string.Privacy_Policy), () -> {

            openWebView(BaseURL.PRIVACY_POLICY, getString(R.string.Privacy_Policy));
        });

        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setText(spannableString);
        init();
    }

    private void startCountDown() {
        btnSendCode.setEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            public void onTick(long millisUntilFinished) {
                btnSendCode.setText(getString(R.string.resend_code_in, millisUntilFinished / 1000));
            }

            public void onFinish() {
                btnSendCode.setText(R.string.send_code);
                btnSendCode.setEnabled(true);
            }
        }.start();
    }

    private void setSpanWithClickAndColor(SpannableString spannableString, String textToHighlight, Runnable onClickAction) {
        int startIndex = spannableString.toString().indexOf(textToHighlight);
        int endIndex = startIndex + textToHighlight.length();
        if (startIndex == -1) return;


        spannableString.setSpan(new ForegroundColorSpan(Color.BLUE), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                onClickAction.run();
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
        }, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    private void openWebView(String url, String title) {
        Intent intent = new Intent(this, Mutual.class);
        intent.putExtra("str1", url);
        intent.putExtra("str2", title);
        startActivity(intent);
    }


    private void init() {

        register.setOnClickListener(v -> {
            if (!checkbox_agree.isChecked()) {

                if (currentToast != null) {
                    currentToast.cancel();
                }
                currentToast = Toast.makeText(this, R.string.Please_read_and_agree_to_the_Privacy_Policy_first, Toast.LENGTH_SHORT);
                currentToast.show();
                return;
            }
            registerUser();
        });

        user_email.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!isValidEmail(user_email.getText().toString())) {
                    user_email.setError(getString(R.string.invalid_email_address));
                }
            }
        });

        login.setOnClickListener(v -> {
            Intent intent = new Intent(this, Login.class);
            startActivity(intent);
//            overridePendingTransition(R.anim.slide_up, R.anim.slide_down);
            finish();
            Register.super.finish();
        });
    }

    private void registerUser() {
        showLoading();
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            String name = user_name.getText().toString().trim();
            String email = user_email.getText().toString().trim();
            String psw = et_psw.getText().toString().trim();
            String cpsw = et_cpsw.getText().toString().trim();
            userInputCode = ((EditText) findViewById(R.id.verification_code)).getText().toString().trim();

            // 验证所有输入字段
            if (!validateInputs(name, email, psw, cpsw, userInputCode)) {
                // 如果验证失败，validateInputs已经显示了错误消息并停止了加载
                return;
            }

            // 验证验证码
            if (!validateVerificationCode(email, userInputCode)) {
                // 如果验证码验证失败，validateVerificationCode已经显示了错误消息并停止了加载
                return;
            }

            // 所有验证通过，继续注册流程
            RegisterDto registerDto = new RegisterDto();
            registerDto.setName(name);
            registerDto.setEmail(email);
            registerDto.setPassword(psw);

            // 调用网络请求注册用户
            performRegistration(registerDto, name);

        }, 1000);
    }

    /**
     * 验证所有用户输入
     */
    private boolean validateInputs(String name, String email, String psw, String cpsw, String code) {
        // 检查验证码是否为空
        if (code.isEmpty()) {
            showToast(R.string.Please_enter_the_verification_code);
            verification_code.setError(getString(R.string.Please_enter_the_verification_code));
            hideLoading();
            return false;
        }

        // 检查必填字段
        if (name.isEmpty() || email.isEmpty() || psw.isEmpty() || cpsw.isEmpty()) {
            showRegisterDialog(getString(R.string.Please_d_leave_it_blank), false);
            hideLoading();
            return false;
        }

        // 验证邮箱格式
        if (!isValidEmail(email)) {
            showRegisterDialog(getString(R.string.invalid_email_address), false);
            user_email.setError(getString(R.string.invalid_email_address));
            hideLoading();
            return false;
        }

        // 验证密码一致性
        if (!psw.equals(cpsw)) {
            showRegisterDialog(getString(R.string.The_password_is_inconsistent_twice), false);
            et_cpsw.setError(getString(R.string.The_password_is_inconsistent_twice));
            hideLoading();
            return false;
        }

        return true;
    }

    /**
     * 验证验证码
     * 注意：在您分享的代码片段中，条件是 `if (!SendGmail.isCodeValid(email))`，
     * 但错误信息表明验证码被判定为过期，这可能表示 isCodeValid 方法的含义与名称相反
     */
    private boolean validateVerificationCode(String email, String inputCode) {
        // ⚠️ 原有判断条件，可能存在逻辑反转问题
        // if (!SendGmail.isCodeValid(email)) {

        // ✅ 修正判断条件 - 这里假设 SendGmail.isCodeValid 方法返回 true 表示验证码已过期
        // 根据您描述的情况修改判断条件
        if (SendGmail.isCodeValid(email)) {
            showToast(R.string.Verification_code_has_expired);
            verification_code.setError(getString(R.string.Verification_code_has_expired));
            hideLoading();
            return false;
        }

        // 获取存储的验证码
        String verificationCode = SendGmail.getVerificationCode(email);
        if (verificationCode == null || verificationCode.isEmpty()) {
            showToast(R.string.Verification_code_has_expired);
            verification_code.setError(getString(R.string.Verification_code_has_expired));
            hideLoading();
            return false;
        }

        // 解析验证码格式 (如果格式是 "email:code")
        String storedCode;
        if (verificationCode.contains(":")) {
            String[] parts = verificationCode.split(":");

            // 验证邮箱一致性
            if (!email.equals(parts[0])) {
                showToast(R.string.Email_is_incorrect);
                user_email.setError(getString(R.string.Email_is_incorrect));
                hideLoading();
                return false;
            }

            storedCode = parts[1];
        } else {
            // 如果格式已经改变，直接使用返回的验证码
            storedCode = verificationCode;
        }

        // 验证码匹配检查
        if (!inputCode.equals(storedCode)) {
            showToast(R.string.Verification_code_is_incorrect);
            verification_code.setError(getString(R.string.Verification_code_is_incorrect));
            hideLoading();
            return false;
        }

        return true;
    }


    /**
     * 执行注册网络请求
     */
    private void performRegistration(RegisterDto registerDto, String name) {
        NetworkUtils.postRegister(registerDto, new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                Log.d(TAG, response.toString());
                if (response.getCode() == 200) {
                    if (response.getData() != null) {
                        RegisterResponse registerResponse = (RegisterResponse) response.getData();
                        if (registerResponse != null) {
                            if (registerResponse.getNameExits()) {
                                showRegisterDialog(getString(R.string.The_account_already_exists_Please_register_again), false);
                                user_name.setError(getString(R.string.The_account_already_exists_Please_register_again));
                                return;
                            }
                            if (registerResponse.getEmailExits()) {
                                showRegisterDialog(getString(R.string.The_email_address_alread_exists), false);
                                user_email.setError(getString(R.string.The_email_address_alread_exists));
                                return;
                            }
                            if (registerResponse.getSuccess()) {
                                showRegisterDialog(getString(R.string.Registration_Successful), true);
                                logRegistrationEvent(name);
                                return;
                            }
                        }
                    }
                    showRegisterDialog(getString(R.string.Registration_failed_Please_try_again_later), false);
                } else {
                    showRegisterDialog(getString(R.string.Registration_failed_Please_try_again_later), false);
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                Log.d(TAG, throwable.toString());
                showRegisterDialog(getString(R.string.Registration_failed_Please_try_again_later), false);
            }
        });
        hideLoading();
    }

    /**
     * 记录注册事件
     */
    private void logRegistrationEvent(String name) {
        Map<String, Object> eventValues = new HashMap<String, Object>();
        eventValues.put("user-register-account", name);
        AppsFlyerLib.getInstance().logEvent(getApplicationContext(),
                "register", eventValues, new AppsFlyerRequestListener() {
                    @Override
                    public void onSuccess() {
                        Log.d(TAG, "Event sent successfully");
                    }
                    @Override
                    public void onError(int i, @NonNull String s) {
                        Log.d(TAG, "Event failed to be sent:\n" +
                                "Error code: " + i + "\n"
                                + "Error description: " + s);
                    }
                });
    }

    /**
     * 显示Toast消息
     */
    private void showToast(int stringResId) {
        if (current != null) {
            current.cancel();
        }
        current = Toast.makeText(this, stringResId, Toast.LENGTH_SHORT);
        current.show();
    }

    private void showRegisterDialog(String message, boolean flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("PROMPT");
        builder.setMessage(message);
        builder.setPositiveButton("OK", (dialog, which) -> {
            if (flag) {
                Intent intent = new Intent(this, Login.class);
                startActivity(intent);
//                overridePendingTransition(R.anim.slide_out_left, R.anim.slide_in_right);
                dialog.dismiss();
                finish();
                super.finish();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }

    private void showLoading() {
        if (loadingView.getParent() == null) {
            ((ViewGroup) findViewById(android.R.id.content)).addView(loadingView);
            Log.d("LoginActivity", "Loading view added");
        }
    }

    private void hideLoading() {
        ((ViewGroup) findViewById(android.R.id.content)).removeView(loadingView);
    }

    private boolean isValidEmail(String email) {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}
